# import numpy as np
# import cv2

# im = cv2.imread('pp.png')
# imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
# ret,thresh = cv2.threshold(imgray,127,255,0)
# im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# cv2.drawContours(img, contours, -1, (0,255,0), 3)


import numpy as np
import cv2
import predict

img = cv2.imread('ee.png')
# img=cv2.resize(img,(100,100))

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)  
# ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)  
  
img2,contours, hierarchy = cv2.findContours(gray,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) 

# the second contour
# print("len(contours):",len(contours))
for x in range(len(contours)):
    x, y, w, h = cv2.boundingRect(contours[x])
    img1=img.copy()
    # crop, be careful
    img1=img1[y:y+h,x:x+w]
    # cv2.imshow("img", img)  
    # cv2.imshow("img1", img1)  
    # cv2.waitKey(0) 
    # img1=img1(x,y,w,h);
    # img1 = cv2.rectangle(img1, (x, y), (x+w, y+h), (0, 255, 0), 2)
    # cv2.drawContours(img,contours,-1,(0,0,255),3) 
    # cv2.imshow("img", img)  
    # cv2.imshow("img1", img1)  
    # cv2.waitKey(0)  
    size_tmp=(w if w>h else h)
    # print("w:",w)
    # print("h:",h)
    # print("size_tmp:",size_tmp)

    # extend the border for 1/3,the final img will be better
    size_final=4*size_tmp/3
    w_extend=(size_final-w)/2
    h_extend=(size_final-h)/2
    # print("w_extend:",w_extend)
    # print("h_extend:",h_extend)
    constant = cv2.copyMakeBorder(img1, int(h_extend),int(h_extend),int(w_extend),int(w_extend), cv2.BORDER_CONSTANT, value=(0,0,0,0))
    img_final=cv2.resize(constant, (28,28))
    # cv2.imshow("img", img)  
    cv2.imshow("img_final", img_final) 
    predict.predict(np.asarray(img_final))
 
    cv2.waitKey(0) 